package com.example.qrcode.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.qrcode.entity.CurrentData;
import com.example.qrcode.mapper.CurrentDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/device")
@CrossOrigin
public class DeviceDataController {

    @Autowired
    private CurrentDataMapper currentDataMapper;

    /**
     * 分页查询设备数据
     */
    @GetMapping("/query/page")
    public Map<String, Object> queryDeviceDataPage(
            @RequestParam(required = false) String deviceIdentifier,
            @RequestParam(required = false) String serviceId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size) {

        Map<String, Object> result = new HashMap<>();

        try {
            Page<CurrentData> pageParam = new Page<>(page, size);
            QueryWrapper<CurrentData> queryWrapper = new QueryWrapper<>();

            // 设备标识模糊查询
            if (deviceIdentifier != null && !deviceIdentifier.trim().isEmpty()) {
                queryWrapper.like("device_identifier", deviceIdentifier.trim());
            }

            // 服务类型筛选
            if (serviceId != null && !serviceId.isEmpty()) {
                if ("other".equals(serviceId)) {
                    // 其他类型：不是analog和discrete的
                    queryWrapper.notIn("service_id", "analog", "discrete");
                } else {
                    // 指定类型
                    queryWrapper.eq("service_id", serviceId);
                }
            } else {
                // 默认查询analog和discrete
                queryWrapper.in("service_id", "analog", "discrete");
            }

            // 按更新时间倒序排列
            queryWrapper.orderByDesc("update_time");

            Page<CurrentData> pageResult = currentDataMapper.selectPage(pageParam, queryWrapper);

            result.put("code", 0);
            result.put("msg", "查询成功");
            result.put("data", pageResult);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "查询失败: " + e.getMessage());
            result.put("data", null);
        }

        return result;
    }
}
